<template>
	<view>
		<view class="content" @touchstart="hideDrawer">
			<u-loading-page :loading="loadstatus_pic"></u-loading-page>
			<scroll-view class="msg-list" scroll-y="true" :scroll-with-animation="scrollAnimation" :scroll-top="scrollTop" :scroll-into-view="scrollToView" @scrolltoupper="loadHistory" upper-threshold="50">
				<!-- 加载历史数据waitingUI -->
				<view class="loading" v-if="showloading==true">
					<view class="spinner">
						<view class="rect1"></view>
						<view class="rect2"></view>
						<view class="rect3"></view>
						<view class="rect4"></view>
						<view class="rect5"></view>
					</view>
				</view>
				<view class="row" v-for="(row,index) in msgList" :key="index" :id="'msg'+row.msg.id">
					<!-- 系统消息 -->
					<block v-if="row.type=='system'" >
						<view class="system">
							<!-- 文字消息 -->
							<view v-if="row.msg.type=='text'" class="text">
								{{row.msg.content.text}}
							</view>
						</view>
					</block>
					<!-- 用户消息 -->
					<block v-if="row.type=='user'">
						<!-- 自己发出的消息 -->
						<view class="my" v-if="row.msg.is_self==1">
							<!-- 左-消息 -->
							<view class="left">
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="bubble">
									<rich-text :nodes="row.msg.content.text"></rich-text>
									<text class="u-type-info-dark u-font-xs u-p-l-20 " style="color:#FFE41F" v-if="row.msg.is_cun==0">{{ row.msg.ps }}</text>
								</view>
								<!-- 语言消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="length">{{row.msg.content.length}}</view>
									<view class="icon my-voice"></view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
									<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
								</view>
								
							</view>
							<!-- 右-头像 -->
							<view class="right">
								<image :src="row.msg.userinfo.face"></image>
							</view>
						</view>
						<!-- 别人发出的消息 -->
						<view class="other" v-if="row.msg.is_self==0">
							<!-- 左-头像 -->
							<view class="left" >
								<image :src="row.msg.userinfo.face" @tap="linkToBusinessCard(row.msg.userinfo.uid)"></image>
							</view>
							<!-- 右-用户名称-时间-消息 -->
							<view class="right">
								<view class="username">
									<view class="name">{{row.msg.userinfo.username}}</view> <view class="time">{{row.msg.time}}</view>
								</view>
								<!-- 文字消息 -->
								<view v-if="row.msg.type=='text'" class="bubble">
									<rich-text :nodes="row.msg.content.text"></rich-text>
								</view>
								<!-- 语音消息 -->
								<view v-if="row.msg.type=='voice'" class="bubble voice" @tap="playVoice(row.msg)" :class="playMsgid == row.msg.id?'play':''">
									<view class="icon other-voice"></view>
									<view class="length">{{row.msg.content.length}}</view>
								</view>
								<!-- 图片消息 -->
								<view v-if="row.msg.type=='img'" class="bubble img" @tap="showPic(row.msg)">
									<image :src="row.msg.content.url" :style="{'width': row.msg.content.w+'px','height': row.msg.content.h+'px'}"></image>
								</view>

							</view>
						</view>
					</block>
				</view>
			</scroll-view>
		</view>
		<!-- 抽屉栏 -->
		<view class="popup-layer" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- 表情 --> 
			<swiper class="emoji-swiper" :class="{hidden:hideEmoji}" indicator-dots="true" duration="150">
				<swiper-item v-for="(page,pid) in emojiList" :key="pid">
					<view v-for="(em,eid) in page" :key="eid" @tap="addEmoji(em)">
						<image mode="widthFix" :src="'https://i.yodin.com/static/emoji/'+em.url"></image>
					</view>
				</swiper-item>
			</swiper>
			<!-- 更多功能 相册-拍照-红包 -->
			<view class="more-layer" :class="{hidden:hideMore}">
				<view class="list">
					<view class="box" @tap="chooseImage"><view class="icon tupian2"></view></view>
					<!--view class="box" @tap="camera"><view class="icon paizhao"></view></view>
					<view class="box" @tap="handRedEnvelopes"><view class="icon hongbao"></view></view-->
				</view>
			</view>
		</view>
		<!-- 底部输入栏 -->
		<view class="input-box" :class="popupLayerClass" @touchmove.stop.prevent="discard">
			<!-- H5下不能录音，输入栏布局改动一下 -->
			<!-- #ifndef H5 -->
			<view class="voice">
				<view class="icon" :class="isVoice?'jianpan':'yuyin'" @tap="switchVoice"></view>
			</view>
			<!-- #endif -->
			<!-- #ifdef H5 -->
			<view class="more" @tap="showMore">
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<view class="textbox">
				<view class="voice-mode" :class="[isVoice?'':'hidden',recording?'recording':'']" @touchstart="voiceBegin" @touchmove.stop.prevent="voiceIng" @touchend="voiceEnd" @touchcancel="voiceCancel">{{voiceTis}}</view>
				<view class="text-mode"  :class="isVoice?'hidden':''">
					<view class="box">
						<textarea auto-height="true" v-model="textMsg" @focus="textareaFocus"/>
					</view>
					<view class="em" @tap="chooseEmoji">
						<view class="icon biaoqing"></view>
					</view>
				</view>
			</view>
			<!-- #ifndef H5 -->
			<view class="more" @tap="showMore">
				<view class="icon add"></view>
			</view>
			<!-- #endif -->
			<view class="send" :class="isVoice?'hidden':''" @tap="sendText">
				<view class="btn">{{$t('send')}}</view>
			</view>
		</view>
		<!-- 录音UI效果 -->
		<view class="record" :class="recording?'':'hidden'">
			<view class="ing" :class="willStop?'hidden':''"><view class="icon luyin2" ></view></view>
			<view class="cancel" :class="willStop?'':'hidden'"><view class="icon chehui" ></view></view>
			<view class="tis" :class="willStop?'change':''">{{recordTis}}</view>
		</view>
	</view>
</template>
<script>
import socket from '@/plugins/socket.js';
import {mapState,mapMutations} from 'vuex';
import { api_chat_friendlist,api_chat_sendmsg,api_chat_listmsg,api_chat_create_roomgroup } from '@/config/api.js';
import { chooseImage,uploadFilePromise } from '@/plugins/upload/upload';
	export default {
		data() {
			return {
				p:1,
				roomid:'',
				showloading:false,
				//文字消息
				textMsg:'',
				//消息列表
				isHistoryLoading:false,
				scrollAnimation:false,
				scrollTop:0,
				scrollToView:'',
				msgList:[],
				msgImgList:[],
				myuid:0,
				loadstatus_pic:false,//全图时
				//录音相关参数
				// #ifndef H5
				//H5不能录音
				RECORDER:uni.getRecorderManager(),
				// #endif
				isVoice:false,
				voiceTis:'按住 说话',
				recordTis:"手指上滑 取消发送",
				recording:false,
				willStop:false,
				initPoint:{identifier:0,Y:0},
				recordTimer:null,
				recordLength:0,
				
				//播放语音相关参数
				AUDIO:uni.createInnerAudioContext(),
				playMsgid:null,
				VoiceTimer:null,
				// 抽屉参数
				popupLayerClass:'',
				// more参数
				hideMore:true,
				//表情定义
				hideEmoji:true,
				emojiList:[
					[{"url":"100.gif?2",alt:"[smile]"},{"url":"101.gif?2",alt:"[naughty]"},]				
				],
				//红包相关参数
				windowsState:'',
			};
		},
	computed: {
	  ...mapState(['userInfo']),
	},
	created() {
		let _this=this;
		this.messageList=[];
		socket.acceptMessage = function(res){
			
			let ress=res;
			if (ress.type=='login'&&ress.client_name==_this.userInfo.username){
				_this.my_client_id=ress.client_id;
			}
			
			if (ress.type=='say'){
				if (ress.from_client_id!=_this.my_client_id){
					//如果收到别人来的信息
					//console.log('_this.my_client_id',_this.my_client_id)
					let nowDate = new Date();
					let msg = {
						type:'user',
						msg:{
							id:Date.now(),
							time:nowDate.getHours()+":"+nowDate.getMinutes(),
							type:ress.msgtype,
							is_self:0,
							userinfo:{
								uid:_this.my_client_id,
								username:ress.username,
								face:ress.avatar,
							},
							content:{
								text:ress.content
							},
						},
					}
					// 发送消息
					_this.screenMsg(msg);
				}
			}
		}
	},
	async onLoad(option) {
        //let query = JSON.parse(decodeURIComponent(option.query));
		this.myuid=this.userInfo.member_id
		this.roomid=option.messageId;
		if (this.roomid!=''){
			socket.send({
				type: "login",
				content: this.$t('signin_login'),
				client_id:this.userInfo.member_id,
				client_name:this.userInfo.username,
				room_id:option.messageId
			}, () => {
				console.log('chat login ok');
			});

			let zt= await this.createroom(option)
			if(zt)this.getMsgList();	
		}else{
			this.$tools.msg("room null");return;
		}
		

		},
		onShow(){
			this.scrollTop = 9999999;
		},
		methods:{
			createroom(option){
				return new Promise((resolve, reject) => {
					api_chat_create_roomgroup( {
						roomnumber:this.roomid,
						form_uid:this.userInfo.member_id,
						roomname:option.roomname
				}).then(res => {
					console.log('res',res)
						uni.setNavigationBarTitle({title: res.roomname});
						this.is_cun=res.is_cun;
						resolve(true);
				}).catch((e)=>{});
				});	
			},
			// 接受消息(筛选处理)
			screenMsg(msg){
				//从长连接处转发给这个方法，进行筛选处理

				if(msg.type=='system'){
					// 系统消息
					switch (msg.msg.type){
						case 'text':
							this.addSystemTextMsg(msg);
							break;
					}
				}else if(msg.type=='user'){
					// 用户消息
					switch (msg.msg.type){
						case 'text':
						console.log('用户消息');
							this.addTextMsg(msg);
							break;
						case 'voice':
							this.addVoiceMsg(msg);
							break;
						case 'img':
							this.addImgMsg(msg);
							break;
					}
					
					//非自己的消息震动

					if(msg.msg.userinfo.uid!=this.myuid){
						console.log('振动');
						uni.vibrateLong();
					}
				}
				this.$nextTick(function() {
					// 滚动到底
					this.scrollToView = 'msg'+msg.msg.id
				});
			},
			
			//触发滑动到顶部(加载历史信息记录)
			async loadHistory(e){
				if(this.isHistoryLoading){
					return ;
				}
				this.isHistoryLoading = true;//参数作为进入请求标识，防止重复请求
				this.scrollAnimation = false;//关闭滑动动画
				let Viewid = this.msgList[0].msg.id;//记住第一个信息ID
				let arr= await this.getMessageData();
				if (arr){
						let list = [];
						for(let i=0;i<arr.length;i++){
							list.unshift(arr[i])
						}
						//本地模拟请求历史记录效果
						setTimeout(()=>{
							// 获取消息中的图片,并处理显示尺寸
							for(let i=0;i<list.length;i++){
								if(list[i].type=='user'&&list[i].msg.type=="img"){
									list[i].msg.content = this.setPicSize(list[i].msg.content);
									this.msgImgList.unshift(list[i].msg.content.url);
								}
								list[i].msg.id = Math.floor(Math.random()*1000+1);
								this.msgList.unshift(list[i]);
							}
							//这段代码很重要，不然每次加载历史数据都会跳到顶部
							this.$nextTick(function() {
								this.scrollToView = 'msg'+Viewid;//跳转上次的第一行信息位置
								this.$nextTick(function() {
									this.scrollAnimation = true;//恢复滚动动画
								});
							});
							this.isHistoryLoading = false;
						},100)
				}
				
			},
			
		//获取消息
		getMessageData() {
			let getData = () => {
				let arr = [];
                api_chat_listmsg({
						roomid:this.roomid,
						p:this.p,
						limit:10
					}).then(res => {
						console.log('res_get',res)
						if (this.p<=res.pages){
							for (let i = 0; i < res.list.length; i++) {
								//const isItMe = res.data.list[i].form_uid ==this.user.userInfo.users_id ? true : false;
								arr.unshift({
									type:"user",
									msg:{
										id:res.list[i].id,
										type:res.list[i].type,
										time:res.list[i].add_time,
										ps: res.list[i].ps,
										is_self:res.list[i].is_self,
										userinfo:{
											uid:res.list[i].form_uid,
											username:res.list[i].username,
											face:res.list[i].avatar,
										},
										content:{
											text:res.list[i].message,
											url:res.list[i].img,
											},
										}
								});
							}
							if (this.p==1){
								//arr.push({type:"system",msg:{id:999,type:"text",content:{text:"建议关注公众号，有新消息时及时通知。"}}})
								
							}
							this.p++;
						}
						if (res.count>(this.p*10)){
							//this.showloading=true;
						}
                    }).catch((e)=>{});
					
				return arr;
			};
			return new Promise((resolve, reject) => {
				const data = getData();
				setTimeout(() => {
					resolve(data);
				}, 300);
			});
		},
			// 加载初始页面消息
			async getMsgList(){
				
				// 消息列表
				// let list = [
				// 	{type:"system",msg:{id:0,type:"text",content:{text:"欢迎进入HM-chat聊天室"}}},
				// 	{type:"user",msg:{id:1,type:"text",time:"12:56",userinfo:{uid:0,username:"大黑哥",face:"/static/img/face.jpg"},content:{text:"为什么温度会相差那么大？"}}},
				// 	{type:"user",msg:{id:3,type:"voice",time:"12:59",userinfo:{uid:1,username:"售后客服008",face:"/static/img/im/face/face_2.jpg"},content:{url:"/static/voice/1.mp3",length:"00:06"}}},
				// 	{type:"user",msg:{id:5,type:"img",time:"13:05",userinfo:{uid:0,username:"大黑哥",face:"/static/img/face.jpg"},content:{url:"/static/img/p10.jpg",w:200,h:200}}},
				// ]
				
				let list= await this.getMessageData();
				console.log('getmsg',list)
				if (list){
						// 获取消息中的图片,并处理显示尺寸
						for(let i=0;i<list.length;i++){
							if(list[i].type=='user'&&list[i].msg.type=="img"){
								list[i].msg.content = this.setPicSize(list[i].msg.content);
								this.msgImgList.push(list[i].msg.content.url);
							}
						}
						
						this.msgList = list;
						// 滚动到底部
						this.$nextTick(function() {
							//进入页面滚动到底部
							this.scrollTop = 9999;
							this.$nextTick(function() {
								this.scrollAnimation = true;
							});
						});
				}
				

			},
			//处理图片尺寸，如果不处理宽高，新进入页面加载图片时候会闪
			setPicSize(content){
				// 让图片最长边等于设置的最大长度，短边等比例缩小，图片控件真实改变，区别于aspectFit方式。
				let maxW = uni.upx2px(350);//350是定义消息图片最大宽度
				let maxH = uni.upx2px(350);//350是定义消息图片最大高度
				if(content.w>maxW||content.h>maxH){
					let scale = content.w/content.h;
					content.w = scale>1?maxW:maxH*scale;
					content.h = scale>1?maxW/scale:maxH;
				}
				return content;
			},
			
			//更多功能(点击+弹出) 
			showMore(){
				this.isVoice = false;
				this.hideEmoji = true;
				if(this.hideMore){
					this.hideMore = false;
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			// 打开抽屉
			openDrawer(){
				this.popupLayerClass = 'showLayer';
			},
			// 隐藏抽屉
			hideDrawer(){
				this.popupLayerClass = '';
				setTimeout(()=>{
					this.hideMore = true;
					this.hideEmoji = true;
				},150);
			},
			// 选择图片发送
			chooseImage(){
				this.getImage('album');
			},
			//拍照发送
			camera(){
				this.getImage('camera');
			},
			//选照片 or 拍照
			getImage(type){
				this.hideDrawer();
				this.loadstatus_pic=true
				let uppicresult=[]
				uni.chooseImage({
					sourceType:[type],
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					success: async(res)=>{
						for(let i=0;i<res.tempFilePaths.length;i++){
							uppicresult = await uploadFilePromise(res.tempFilePaths[i],3)
							if (uppicresult.bid>0){
								uni.getImageInfo({
									src: res.tempFilePaths[i],
									success: (image)=>{
										let msg = {url:uppicresult.file_path,img:uppicresult.file_url,w:image.width,h:image.height};
										this.sendMsg(msg,'img');
									}
								});
								this.loadstatus_pic=false
							}

						}
					}
				});
			},
			// 选择表情
			chooseEmoji(){
				this.hideMore = true;
				if(this.hideEmoji){
					this.hideEmoji = false;
					this.openDrawer();
				}else{
					this.hideDrawer();
				}
			},
			//添加表情
			addEmoji(em){
				this.textMsg+=em.alt;
			},
			
			//获取焦点，如果不是选表情ing,则关闭抽屉
			textareaFocus(){
				if(this.popupLayerClass=='showLayer' && this.hideMore == false){
					this.hideDrawer();
				}
			},
			// 发送文字消息
			sendText(){
				this.hideDrawer();//隐藏抽屉
				if(!this.textMsg){
					return;
				}
				let content = this.replaceEmoji(this.textMsg);
				let msg = {text:content}
				this.sendMsg(msg,'text');
				this.textMsg = '';//清空输入框
			},
			//替换表情符号为图片
			replaceEmoji(str){
				let replacedStr = str.replace(/\[([^(\]|\[)]*)\]/g,(item, index)=>{
					console.log("item: " + item);
					for(let i=0;i<this.emojiList.length;i++){
						let row = this.emojiList[i];
						for(let j=0;j<row.length;j++){
							let EM = row[j];
							if(EM.alt==item){
								//在线表情路径，图文混排必须使用网络路径，请上传一份表情到你的服务器后再替换此路径 
								//比如你上传服务器后，你的100.gif路径为https://www.xxx.com/emoji/100.gif 则替换onlinePath填写为https://www.xxx.com/emoji/
								let onlinePath = 'https://i.yodin.com/static/emoji/'
								let imgstr = '<img src="'+onlinePath+EM.url+'">';
								console.log("imgstr: " + imgstr);
								return imgstr;
							}
						}
					}
				});
				//return '<div style="display: flex;align-items: center;word-wrap:break-word;">'+replacedStr+'</div>';
				return replacedStr;
			},
			
			// 发送消息
			sendMsg(content,type){
				
				//实际应用中，此处应该提交长连接，模板仅做本地处理。
				var nowDate = new Date();
				let lastid = this.msgList[this.msgList.length-1].msg.id;
				let aliasname
				aliasname=this.userInfo.username
				let txt_img_msg=""
				let local_img_msg=""
				if (type=='text'){
					txt_img_msg=content.text
					local_img_msg=content.text
				}
				if (type=='img'){
					txt_img_msg=content.url
					local_img_msg=content.img //带网址的图片
					content.url=content.img
				}

				socket.send({
					type: "say",
					msgtype:type,
					content: local_img_msg,
					to_client_id:'all',
					room_id:this.roomid,
					to_client_name:this.userInfo.member_id,
					aliasname:aliasname,
					avatar:this.userInfo.avatar_url
				},() => {
					api_chat_sendmsg( {
							message:txt_img_msg,
							type:type,
							roomid:this.roomid
						}).then(res => {
							lastid=res
							
						this.$nextTick(function() {
							// 滚动到底
							this.scrollToView = 'msg'+lastid
						});
							
						}).catch((e)=>{});
				});
				
				//lastid++;
				let msgdata = {
					type:'user',
					msg:{
						id:lastid,
						time:nowDate.getHours()+":"+nowDate.getMinutes(),
						type:type,
						is_self:1,
						ps:'[未读]',
						userinfo:{
							uid:this.userInfo.member_id,
							username:this.userInfo.username,
							face:this.userInfo.avatar_url,
						},
						content:content,
						},
					}

				// 发送消息
				this.screenMsg(msgdata);


			},
			
			// 添加文字消息到列表
			addTextMsg(msg){
				this.msgList.push(msg);
			},
			// 添加语音消息到列表
			addVoiceMsg(msg){
				this.msgList.push(msg);
			},
			// 添加图片消息到列表
			addImgMsg(msg){
				msg.msg.content = this.setPicSize(msg.msg.content);
				this.msgImgList.push(msg.msg.content.url);
				this.msgList.push(msg);
			},
			addRedEnvelopeMsg(msg){
				this.msgList.push(msg);
			},
			// 添加系统文字消息到列表
			addSystemTextMsg(msg){
				this.msgList.push(msg);
			},

			sendSystemMsg(content,type){
				let lastid = this.msgList[this.msgList.length-1].msg.id;
				lastid++;
				let row = {type:"system",msg:{id:lastid,type:type,content:content}};
				this.screenMsg(row)
			},

			// 预览图片
			showPic(msg){
				uni.previewImage({
					indicator:"none",
					current:msg.content.url,
					urls: this.msgImgList
				});
			},
			
			discard(){
				return;
			},
		linkToBusinessCard(uid) {
			this.$Router.push({
				path: '/pages/componentsB/chat/businessCard',
				query: { usersid:uid}
			});
		},
		
		}
	}
</script>
<style lang="scss">
	@import "./style.scss"; 
</style>